package top.jolyoulu.codegenweb.service.bll.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.jolyoulu.codegenweb.config.SecurityConfig;
import top.jolyoulu.codegenweb.entity.bo.form.DataSourceInfoFormBO;
import top.jolyoulu.codegenweb.entity.bo.query.DataSourceInfoQueryBO;
import top.jolyoulu.codegenweb.entity.po.DataSourceInfo;
import top.jolyoulu.codegenweb.entity.vo.DataSourceInfoVO;
import top.jolyoulu.codegenweb.service.bll.ApiDataSourceService;
import top.jolyoulu.codegenweb.service.dal.DataSourceInfoService;
import top.jolyoulu.corecommon.utils.encryption.DESUtils;
import top.jolyoulu.modules.druidmodule.utils.datasource.DruidUtils;
import top.jolyoulu.modules.mybatisplusmodule.plugin.page.JlPage;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: JolyouLu
 * @Date: 2023/3/25 15:48
 * @Description
 */
@Slf4j
@Service
public class ApiDataSourceServiceImpl implements ApiDataSourceService {

    @Autowired
    private DataSourceInfoService dataSourceInfoService;

    @Autowired
    private SecurityConfig securityConfig;

    @Override
    public JlPage<DataSourceInfoVO> pageList(DataSourceInfoQueryBO bo) {
        return JlPage.execute(bo.getPage(),bo.getPageSize(),() -> {
            List<DataSourceInfo> list = dataSourceInfoService.list();
            return list.stream().map(DataSourceInfoVO::new).collect(Collectors.toList());
        });
    }

    @Override
    public DataSourceInfoVO getById(String id) {
        DataSourceInfo res = dataSourceInfoService.getById(id);
        return new DataSourceInfoVO(res);
    }

    @Override
    public void add(DataSourceInfoFormBO bo) {
        DataSourceInfo dataSourceInfo = new DataSourceInfo();
        BeanUtils.copyProperties(bo,dataSourceInfo);
        //密码加密
        String decryptPwd = DESUtils.encrypt(bo.getPassword(), securityConfig.getPwdSecretKey());
        dataSourceInfo.setPassword(decryptPwd);
        dataSourceInfoService.save(dataSourceInfo);
    }

    @Override
    public void update(DataSourceInfoFormBO bo) {
        DataSourceInfo dataSourceInfo = new DataSourceInfo();
        BeanUtils.copyProperties(bo,dataSourceInfo);
        //密码加密
        if (StringUtils.isNotBlank(dataSourceInfo.getPassword())){
            String decryptPwd = DESUtils.encrypt(bo.getPassword(), securityConfig.getPwdSecretKey());
            dataSourceInfo.setPassword(decryptPwd);
        }
        //关闭数据源
        DruidUtils.cloDataSource(bo.getId());
        dataSourceInfoService.updateById(dataSourceInfo);
    }

    @Override
    public void delByIds(List<String> ids) {
        for (String id : ids) {
            //关闭数据源
            DruidUtils.cloDataSource(id);
            //删除数据
            dataSourceInfoService.removeById(id);
        }
    }

}
